package com.purengage.ipilih;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.ActionText;
import com.markupartist.android.widget.ActionBar.IntentAction;
import com.markupartist.android.widget.ActionBar.IntentActionText;
import com.purengage.ipilih.lib.CustomAdapter;
import com.purengage.ipilih.lib.DBClass;
import com.purengage.ipilih.lib.HttpConnect;
import com.purengage.ipilih.lib.Komen;
import com.purengage.ipilih.lib.Msg;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class Komentar extends Activity {
	ProgressBar progress;

	public class komentar extends AsyncTask<String, String, Boolean> {
		DBClass db = new DBClass(Komentar.this);
		private ProgressDialog dialog = new ProgressDialog(Komentar.this);
		Bundle extras = getIntent().getExtras();
		int id = extras.getInt("id");
		String to_status_id = "";

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			
			String dateModif = (db.getDateLastKomen(id).equalsIgnoreCase("")) ? "2013-11-1"
					: db.getDateLastKomen(id);

			String uri = "http://purengage.com/api/statuses/id/" + id
					+ "?client_id="
					+ getResources().getString(R.string.client_id) + "&token="
					+ db.getValue("token") + "&indent=" + params[0] + "&count="
					+ params[1] + "&since_date_modified="
					+ dateModif.replaceAll("\\s+", "%20");
			HttpConnect http = new HttpConnect(uri);
			String output = "";

			boolean res = http.getData();
			if (res) {
				output = http.getOutput();
				Log.d("--komentar--", output);
				Log.d("id", id + "");
				Log.d("uri", uri);

				JSONObject jobj;
				try {
					jobj = new JSONObject(output);
					JSONArray json = jobj.getJSONArray("data");

					for (int i = 0; i < json.length(); i++) {
						JSONObject job = json.getJSONObject(i);
						to_status_id = job.getString("reply_to_status_id");
						Komen k = new Komen();
						k.setId(job.getInt("id"));
						k.setMessage(job.getString("message"));
						k.setDate_created(job.getString("date_modified"));
						k.setFrom_user_name(job
								.getString("from_volunteer_name"));
						k.setReply_to_status_id(to_status_id);
						if (!to_status_id.equals("0"))
							db.insertKomen(k);
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			return res;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			progress.setVisibility(View.GONE);
			if (!result)
				Toast.makeText(
						Komentar.this,
						"Tidak dapat menghubungi server, periksa setting internet anda",
						Toast.LENGTH_LONG).show();
			else
				loadKomen(to_status_id);
		}

	}

	public class postkomentar extends AsyncTask<String, String, Boolean> {
		DBClass db = new DBClass(Komentar.this);
		private ProgressDialog dialog = new ProgressDialog(Komentar.this);

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			HttpConnect http = new HttpConnect(
					"http://purengage.com/api/statuses", 5);
			http.addVar("client_id",
					getResources().getString(R.string.client_id));
			http.addVar("token", db.getValue("token"));
			http.addVar("indent", "1");
			String message = params[0].replace(" ", "%20");
			http.addVar("message", message);
			http.addVar("reply_to_status_id", params[1]);
			
			if(params[0].equalsIgnoreCase(""))
				return false;
			
			boolean res = http.postData();
			if (res) {
				try {
					JSONArray re = new JSONArray("[" + http.getOutput() + "]");
					Log.d("array", re.toString());
				} catch (Exception e) {					
					e.printStackTrace();
				}
			}
			return res;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			dialog.setMessage("Loading..");
			dialog.show();

		}

		@Override
		protected void onPostExecute(Boolean result) {			
			super.onPostExecute(result);
			dialog.dismiss();
			finish();
		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_komentar);
		progress = (ProgressBar) findViewById(R.id.statusProgress);

		final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setTitle("Komentar");
		actionBar.setHomeAction(new IntentAction(this, Relawan
				.createIntent(this), R.drawable.ic_action_back));
		Bundle extras = getIntent().getExtras();
		final int id = extras.getInt("id");
		TextView name = (TextView) findViewById(R.id.txtName);
		TextView date = (TextView) findViewById(R.id.txtDate);
		TextView msg = (TextView) findViewById(R.id.txtMsg);
		Button post = (Button) findViewById(R.id.post_komen);
		DBClass db = new DBClass(getApplicationContext());
		Msg m = db.getMsgById(id);

		name.setText(m.getUser());
		date.setText(m.getDate());
		msg.setText(m.getMessage());

		String[] params = { "1", "50" };
		new komentar().execute(params);
		

		post.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {				
				//Toast.makeText(Komentar.this, "Send komentar.",
				//		Toast.LENGTH_SHORT).show();
				
				PostMessage(id);
			}
		});

	}

	public void PostMessage(int id) {
		EditText msg = (EditText) findViewById(R.id.etextKomen);
		String isikomen = msg.getText().toString();
		String[] params = { isikomen, String.valueOf(id) };
		new postkomentar().execute(params);

	}

	public void loadKomen(String to_status_id) {
		progress.setVisibility(View.GONE);
		DBClass db = new DBClass(this);
		List<Komen> dataList;

		if (!to_status_id.equals("0")) {
			ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
			dataList = db.getListKomen(Integer.parseInt(to_status_id));

			ListAdapter adapter;
			ListView lv = (ListView) findViewById(R.id.listk);
			for (Komen km : dataList) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("name", km.getFrom_user_name());
				map.put("message", km.getMessage());
				map.put("date", km.getDate_created());
				list.add(map);
			}

			adapter = new CustomAdapter(this, list, R.layout.row_komenlist,
					new String[] { "name", "message", "date" }, new int[] {
							R.id.textName, R.id.textKomen, R.id.textDate });
			Log.d("list", list.toString());
			lv.setAdapter(adapter);
		}

	}

}
